package com.youth.hrsync.controller;

import org.springframework.batch.core.*;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class IndexController {

    @Autowired
    JobLauncher jobLauncher;

    @Autowired
    JobExplorer jobExplorer;

    @Autowired
    Job hrJob;

    @GetMapping("whoAmI")
    public String whoAmI() {
        return "I am a hr sync batch service.";
    }

    @GetMapping("/run")
    public ExitStatus run() throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException, JobParametersInvalidException, JobRestartException {
        System.out.println("runTask");
        System.out.println(hrJob);
        JobParameters parameters = new JobParametersBuilder(jobExplorer)
                .getNextJobParameters(hrJob)
                .addDate("excuTime", new Date())
                .toJobParameters();
        System.out.println(parameters);
        JobExecution jobExecution = jobLauncher.run(hrJob, parameters);
        return jobExecution.getExitStatus();
//        return "";
    }

}
